package com.sptpc.learnspring.controller;

import com.sptpc.learnspring.controller.request.NewDrinkRequest;
import com.sptpc.learnspring.model.Drink;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/drink")
public class DrinkController {

    @GetMapping("/")
    public List<Drink> listDrinks() {
        log.info("查询饮品菜单");
        List<Drink> list = new ArrayList<>();
        list.add(Drink.builder().id(1).name("茉莉绿茶").price(BigDecimal.valueOf(8.00)).build());
        list.add(Drink.builder().id(2).name("四季春茶").price(BigDecimal.valueOf(8.00)).build());
        return list;
    }

    @PostMapping("/")
    // 函数参数需与前端http参数名字相同
    public List<Drink> searchDrinks(String key) {
        log.info("搜索饮品 key: {}", key);
        return new ArrayList<>();
    }

    @GetMapping("/{id}")
    // 函数参数需与注解中path参数名相同
    public Drink getDrink(@PathVariable Integer id) {
        log.info("搜索饮品 id: {}", id);
        return Drink.builder()
                .id(2)
                .name("四季春茶")
                .price(BigDecimal.valueOf(8.00))
                .build();
    }

    // 前端使用html表单提交数据
    @PostMapping(value = "/add", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
    public Drink addNewDrinkForHtmlForm(NewDrinkRequest newDrink) {
        log.info("创建新饮品{}", newDrink);
        Drink drink = new Drink();
        BeanUtils.copyProperties(newDrink, drink);
        drink.setId(1);
        log.info("创建成功");
        return drink;
    }

    // 前端使用json提交数据
    @PostMapping(value = "/add", consumes = {MediaType.APPLICATION_JSON_VALUE})
    public Drink addNewDrink(@RequestBody NewDrinkRequest newDrink) {
        log.info("创建新饮品{}", newDrink);
        Drink drink = new Drink();
        BeanUtils.copyProperties(newDrink, drink);
        drink.setId(2);
        log.info("创建成功");
        return drink;
    }
    
}
